package test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioClient {
	
	private static ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
	
	private static SocketChannel socketChannel;
	
	public static void main(String[] args) throws Exception{
		
		Selector selector = Selector.open();
		socketChannel = SocketChannel.open();
		socketChannel.configureBlocking(false);
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9000);
		boolean result = socketChannel.connect(address);
		
		if (result) {
			socketChannel.register(selector, SelectionKey.OP_READ);
			writeData("test");
		}else{
			socketChannel.register(selector, SelectionKey.OP_CONNECT);
		}
		
		while(true){
			int num = selector.select(500);
			if (num > 0) {
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				
				for (Iterator<SelectionKey> iterator = selectionKeys.iterator(); iterator.hasNext();) {
					SelectionKey selectionKey = iterator.next();
					iterator.remove();
					if (selectionKey.isValid()) {
						if (selectionKey.isConnectable()) {
							if (socketChannel.finishConnect()) {
								socketChannel.register(selector, SelectionKey.OP_READ);
								writeData("test");
							}else{
								System.out.println("连接失败，");
								System.exit(0);
							}
							
						}
						if (selectionKey.isReadable()) {
							buffer.clear();
							int num1 = socketChannel.read(buffer);
							
							if (num1 == 0) {
								continue;
							}
							buffer.flip();
							byte[] bs = new byte[num1];
							buffer.get(bs);
							System.out.println(new String(bs));
						}
						if (selectionKey.isWritable()) {
							
						}
						
					}
				}
			}
		}
		
		
		
	}

	private static void writeData(String data) throws IOException{
		buffer.clear();
		buffer.put(data.getBytes());
		buffer.flip();
		int num = socketChannel.write(buffer);
		System.out.println("write data num" + num);
	}
}
